package com.ruoyi.project.service.impl;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.material.domain.SysUserProject;
import com.ruoyi.material.mapper.SysUserProjectMapper;
import com.ruoyi.wbs.domain.Contractor;
import com.ruoyi.wbs.domain.ProjectActivity;
import com.ruoyi.wbs.mapper.ContractorMapper;
import com.ruoyi.wbs.mapper.ProjectActivityMapper;
import com.ruoyi.wbs.mapper.WbsPlanMapper;
import com.ruoyi.workorder.domain.WorkOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import com.ruoyi.project.mapper.ProjectMapper;
import com.ruoyi.project.domain.Project;
import com.ruoyi.project.service.IProjectService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * 项目Service业务层处理
 * 
 * @author Q
 * @date 2024-05-28
 */
@Service
public class ProjectServiceImpl implements IProjectService 
{
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private SysUserProjectMapper sysUserProjectMapper;
    @Autowired
    private ProjectActivityMapper projectActivityMapper;
    @Autowired
    private ContractorMapper contractorMapper;


    /**
     * 查询项目
     * 
     * @param projectId 项目主键
     * @return 项目
     */
    @Override
    public Project selectProjectByProjectId(Long projectId)
    {
        return projectMapper.selectProjectByProjectId(projectId);
    }

    /**
     * 查询项目列表
     *
     * @param project 项目
     * @return 项目
     */
    @Override
    public List<Project> selectProjectList(Project project)
    {
        return projectMapper.selectProjectList(project);
    }

    /**
     * 新增项目
     * 
     * @param project 项目
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, Error.class})
    public AjaxResult insertProject(Project project)
    {
        LoginUser user = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long userId = user.getUserId();
        int i = projectMapper.insertProject(project);
        if (i > 0) {
            SysUserProject sp = new SysUserProject();
            sp.setUserId(userId);
            sp.setProjectId(project.getProjectId());
            sysUserProjectMapper.insert(sp);
        }

        return AjaxResult.success();
    }

    /**
     * 修改项目
     * 
     * @param project 项目
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, Error.class})
    public int updateProject(Project project)
    {
        //找到数据库里图片
        String dbImage = projectMapper.selectProjectByProjectId(project.getProjectId()).getProjectImage();
        String dbLogo = projectMapper.selectProjectByProjectId(project.getProjectId()).getProjectLogo();
        //修改
        int i = projectMapper.updateProject(project);
       //修改时删除垃圾图片
        if(i>0){
            //前端传过来的图片
            String frontImage = project.getProjectImage();
            String frontLogo = project.getProjectLogo();
            //做判断
            if(!Objects.equals(dbImage,frontImage)){
                //删除数据库里的图片
                String path= dbImage.substring(dbImage.indexOf("/",1));
                File file = new File(RuoYiConfig.getProfile()+path);
                if(file.exists()){
                    file.delete();
                }
            }
            if(!Objects.equals(dbLogo,frontLogo)){
                //删除数据库里的图片
                String path= dbLogo.substring(dbLogo.indexOf("/",1));
                File file = new File(RuoYiConfig.getProfile()+path);
                if(file.exists()){
                    file.delete();
                }
            }
        }

       return i;
    }


    /**
     * 批量删除项目
     *
     * @param projectIds 需要删除的项目主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, Error.class})
    public int deleteProjectByProjectIds(Long[] projectIds)
    {

        return projectMapper.deleteProjectByProjectIds(projectIds);
    }

    /**
     * 删除项目信息 单删
     * 
     * @param projectId 项目主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, Error.class})
    public AjaxResult deleteProjectByProjectId(Long projectId)
    {

        if(projectMapper.selectProjectByProjectId(projectId).getProjectImage()!=null){
            //删除硬盘中的文件
            String imagePath = projectMapper.selectProjectByProjectId(projectId).getProjectImage();
            String imageUrl = imagePath.substring(imagePath.indexOf("/",1));
            File file1 = new File(RuoYiConfig.getProfile()+imageUrl);
            if(file1.exists()){
                file1.delete();
            }
        }
        if(projectMapper.selectProjectByProjectId(projectId).getProjectLogo()!=null){
            String logoPath = projectMapper.selectProjectByProjectId(projectId).getProjectLogo();
            String logoUrl = logoPath.substring(logoPath.indexOf("/",1));
            File file2 = new File(RuoYiConfig.getProfile()+logoUrl);
            if(file2.exists()){
                file2.delete();
            }
        }
        //删除数据库中的数据
        int i = projectMapper.deleteProjectByProjectId(projectId);
           //删除中间表数据
        if (i > 0) {
            sysUserProjectMapper.deleteSysUserProjectByProjectId(projectId);
        }
        return AjaxResult.success();
    }



    @Override
    public List<Project> selectProjectByUserId(Long userId) {
        return projectMapper.selectProjectByUserId(userId);
    }

    @Override
    public List<Project> selectProjectListForUser(Project project, Long userId) {
        return projectMapper.selectProjectListForUser(project,userId);
    }

    /**
     *  项目名称的唯一性验证
     * @param project
     * @return
     */
    @Override
    public boolean checkNameUnique(Project project) {
        Long id= projectMapper.checkNameUnique(project);
        return id!=null;
    }
    /**
     *  项目的有约束删除
     */
    @Override
    public String checkHasData(Long projectId) {
        return projectMapper.checkHasData(projectId);
    }

    @Override
    public Integer[] selectProjectIds(Long userId) {
        return sysUserProjectMapper.selectProjectIds(userId);
    }
    /**
     *  项目和活动的级联
     */
    @Override
    public List<Map<String, Object>> selectCascaderList(Integer[] projectIds) {
        //查询项目
        List<Project> projectList = projectMapper.selectCascaderProjectList(projectIds);
        //封装成级联数据
        List<Map<String, Object>> cascaderList = projectList.stream().map(p -> {
            // 项目创建map
            Map<String, Object> pMap = new HashMap<>();
            pMap.put("value", p.getProjectId());
            pMap.put("label", p.getProjectName());
            //查询活动
            List<ProjectActivity> acts = projectActivityMapper.selectProjectActivityListByProjectId(p.getProjectId());
            List<Map<String, Object>> actList = acts.stream().map(a -> {
                Map<String, Object> actMap = new HashMap<>();
                actMap.put("value", a.getAvtivityId());
                actMap.put("label", a.getActivityName());
                return actMap;
            }).collect(Collectors.toList());
            /// 将活动添加到项目Map
            pMap.put("children", actList);
            return pMap;
        }).collect(Collectors.toList());
        return cascaderList;
    }

    @Override
    public List<Map<String, Object>> selectConCascaderList(Integer[] projectIds) {
        //查询项目
        List<Project> projectList = projectMapper.selectCascaderProjectList(projectIds);
        //封装成级联数据
        List<Map<String, Object> > conCascaderList = projectList.stream()
                .map(p -> {
                    Map<String, Object> proMap = new HashMap<>();
                    proMap.put("value", p.getProjectId());
                    proMap.put("label", p.getProjectName());
                List<Contractor> con = contractorMapper.selectContractorListByProjectId(p.getProjectId());
                List<Map<String, Object>> conList = con.stream().map(c -> {
                        Map<String, Object> conMap = new HashMap<>();
                        conMap.put("value", c.getContractorId());
                        conMap.put("label", c.getContractorName());
                        return conMap;
                    }).collect(Collectors.toList());
                    proMap.put("children", conList);
                return proMap;
        }).collect(Collectors.toList());
        return conCascaderList;
    }

}
